import { ref } from 'vue'

// 创建全局单例
const visible = ref(false)
const config = ref({
  title: '',
  message: '',
  type: 'info',
  showCancel: true,
  showConfirm: true,
  cancelText: '取消',
  confirmText: '确认',
  showContact: false,
  icon: 'info',
  theme: 'light',
  animation: 'fade',
  width: 'auto',
  maxWidth: '500px',
  padding: '24px',
  borderRadius: '12px'
})

// 预设的弹窗配置
const dialogPresets = {
  // 演示功能
  demo: {
    title: '演示功能',
    message: '该功能正在开发中，敬请期待！',
    type: 'info',
    showCancel: false,
    confirmText: '知道了',
    icon: 'info',
    theme: 'light',
    animation: 'fade'
  },
  // 联系方式
  contact: {
    title: '联系我们',
    type: 'info',
    message: '电话：400-XXX-XXXX\n邮箱：contact@example.com',
    showCancel: false,
    confirmText: '关闭',
    showContact: true,
    icon: 'contact',
    theme: 'blue',
    animation: 'slide'
  },
  // 职位申请
  jobApply: {
    title: '申请职位',
    type: 'form',
    showCancel: true,
    confirmText: '提交申请',
    icon: 'job',
    theme: 'blue',
    animation: 'scale'
  },
  // 项目咨询
  projectInquiry: {
    title: '项目咨询',
    type: 'form',
    showCancel: true,
    confirmText: '提交咨询',
    icon: 'project',
    theme: 'blue',
    animation: 'slide'
  }
}

// 当前回调函数
let currentResolve = null
let currentReject = null

export function useDialog() {
  const open = (preset = '', options = {}) => {
    return new Promise((resolve, reject) => {
      // 如果已经有弹窗打开，先关闭它
      if (visible.value) {
        close()
      }

      // 更新配置
      const presetConfig = typeof preset === 'string' ? dialogPresets[preset] || {} : preset
      config.value = {
        title: '',
        message: '',
        type: 'info',
        showCancel: true,
        showConfirm: true,
        cancelText: '取消',
        confirmText: '确认',
        showContact: false,
        icon: 'info',
        theme: 'light',
        animation: 'fade',
        width: 'auto',
        maxWidth: '500px',
        padding: '24px',
        borderRadius: '12px',
        ...presetConfig,
        ...options
      }

      currentResolve = resolve
      currentReject = reject
      visible.value = true
    })
  }

  const close = () => {
    visible.value = false
    if (currentReject) {
      currentReject('Dialog closed')
      currentReject = null
      currentResolve = null
    }
  }

  const confirm = () => {
    if (currentResolve) {
      currentResolve(true)
      currentResolve = null
      currentReject = null
    }
    visible.value = false
  }

  const cancel = () => {
    if (currentReject) {
      currentReject('User cancelled')
      currentReject = null
      currentResolve = null
    }
    visible.value = false
  }

  return {
    visible,
    config,
    open,
    close,
    confirm,
    cancel
  }
}
